package com.lineage.server.timecontroller.quest;

import com.lineage.data.quest.DarkElfLv50_1;
import com.lineage.server.model.Instance.L1MonsterInstance;
import com.lineage.server.model.Instance.L1NpcInstance;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.model.L1Location;
import com.lineage.server.serverpackets.S_EffectLocation;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.templates.L1QuestUser;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.utils.L1SpawnUtil;
import com.lineage.server.world.WorldQuest;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DE50A_Timer extends TimerTask {
  private static final Log _log = LogFactory.getLog(DE50A_Timer.class);
  
  private static Random _random = new Random();
  
  private ScheduledFuture<?> _timer;
  
  private int _qid = -1;
  
  public void start() {
    this._qid = DarkElfLv50_1.QUEST.get_id();
    int timeMillis = 1500;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, 1500L, 1500L);
  }
  
  public void run() {
    try {
      ArrayList<L1QuestUser> questList = WorldQuest.get().getQuests(this._qid);
      if (questList.isEmpty())
        return; 
      Object[] array;
      int length = (array = questList.toArray()).length;
      int i = 0;
      while (i < length) {
        Object object = array[i];
        L1QuestUser quest = (L1QuestUser)object;
        Iterator<L1PcInstance> iterator = quest.pcList().iterator();
        while (iterator.hasNext()) {
          L1PcInstance tgpc = iterator.next();
          if (!tgpc.isDead() && _random.nextInt(100) < 10) {
            quest.addNpc((L1NpcInstance)spawn(tgpc));
            Thread.sleep(50L);
          } 
        } 
        i++;
      } 
      questList.clear();
    } catch (Exception e) {
      _log.error("寻找黑暗之星 (黑暗妖精50级以上官方任务)A时间轴异常重启", e);
      GeneralThreadPool.get().cancel(this._timer, false);
      DE50A_Timer de50ATimer = new DE50A_Timer();
      de50ATimer.start();
    } 
  }
  
  private static L1MonsterInstance spawn(L1PcInstance tgpc) {
    try {
      L1Location loc = tgpc.getLocation().randomLocation(4, false);
      tgpc.sendPackets((ServerBasePacket)new S_EffectLocation(loc, 3992));
      L1MonsterInstance mob = null;
      if (_random.nextBoolean()) {
        mob = L1SpawnUtil.spawnX(45582, loc, tgpc.get_showId());
      } else {
        mob = L1SpawnUtil.spawnX(45587, loc, tgpc.get_showId());
      } 
      mob.setExp(1L);
      return mob;
    } catch (Exception ex) {
      return null;
    } 
  }
}
